<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-03-28
 * Time: 20:46
 */

namespace app\api\service;


use app\api\model\Video as VideoModel;
use LinCmsTp5\admin\model\LinFile;
use think\facade\Request;

class Video
{
    private $filepath;
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    private $md5;
    private $size;

    public function __construct($filepath,$totalBlobNum,$fileName,$md5,$size)
    {
        $this->totalBlobNum = $totalBlobNum;
        $this->fileName = $fileName;
        $this->md5 = $md5;
        $this->filepath = $filepath;
        $this->size = $size;
        $this->fileMerge();
    }

    private function fileMerge()
    {
        // 此处文件不应该拼接，应该是追加入内
        // 实测修改后php占用很少的内存也可以实现大文件的上传和拼接操作
        for($i=0; $i< $this->totalBlobNum; $i++){
            $blob = '';
            if(file_exists($this->filepath . '/' . $this->md5 . '__' . $i)) {
                $blob = file_get_contents($this->filepath . '/' . $this->md5 . '__' . $i);
                file_put_contents($this->filepath . '/' . $this->fileName, $blob, FILE_APPEND);
                unset($blob);
            } else {
                return '';
            }
        }
        $this->deleteFileBlob();
    }

    //删除文件块
    private function deleteFileBlob()
    {
        for($i=0; $i< $this->totalBlobNum; $i++){
            @unlink($this->filepath.'/'. $this->md5.'__'.$i);
        }
    }

    //API返回数据
    public function apiReturn()
    {
        if(file_exists($this->filepath.'/'. $this->fileName)){
            $data['file_name'] = substr($this->fileName,0,strrpos($this->fileName, '.'));
            $data['file_extension'] = substr(strrchr($this->fileName, '.'), 1);
            $extension = '.'.$data['file_extension'];
            $linFile = LinFile::create([
                'name' => $this->fileName,
                'path' => 'videos/'.$this->fileName,
                'extension' => $extension,
                'md5' => $this->md5,
                'type' => 1,
                'size' => $this->size,
            ]);
            VideoModel::create([
                'name' => $this->fileName,
                'url' => 'videos/'.$this->fileName,
                'file_id' => $linFile->id,
                'from' => 1
            ]);
        }
        return [
            'code' => 2000,
            'message'=> '操作成功',
            'data' => ''
        ];
    }
}